<template>
  <div>
    <div id="container">
      <el-form ref="form" :inline="true" :model="form" label-width="80px" style="position:absolute;top:1px;z-index: 100;width: 100%;">
        <el-row>
          <el-col :span="20"> 
            <!-- <el-form-item label="">
              <el-select v-model="form.jd" placeholder="请选择街道" @change="getTimeList">
                <el-option
                  v-for="dict in dict.type.sys_jd_name"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="">
              <el-select v-model="form.fq" placeholder="选择时间点">
                <el-option v-for="item in timeList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="">
              <el-select v-model="showDataType" placeholder="请选择数据类型">
                <el-option
                  v-for="dict in dict.type.sys_data_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="时间点">
              <el-date-picker v-model="form.rq" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
              <el-select v-model="form.hour" placeholder="选择小时">
              <el-option v-for="item in hours" :key="item" :label="item" :value="item"></el-option>
            </el-select>
            </el-form-item> -->
            <el-form-item>
              <!-- <div @click="onSubmit">dddd</div> -->
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <!-- <el-button type="primary" @click="pmShow = !pmShow">查询</el-button> -->
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="input-item">
              <el-button class="btn" id="add-satellite-layer"  @click="changeMap(1)" style="margin-right:1rem;">卫星图层</el-button>
              <el-button class="btn" id="remove-satellite-layer" @click="changeMap(2)" >路网图层</el-button>
            </div>
          </el-col>
        </el-row>
       
        
      </el-form>

      <!-- pm2.5数值展示 -->
      <div class="pmInfo" :class="{'fade-in': pmShow}" v-show="pmShow">
        <div class="header">
          <div class="title">信息</div>
          <i class="el-icon-close" @click="pmShow = false"></i>
        </div>
        <div class="content">
          <div class="pm-item">
            <div class="title">PM2.5</div>
            <div class="value">{{ pmVal }}</div>
          </div>
        </div>
      </div>
    </div>
    <!-- <div><input type="button" value="dd" @click="getAreaPoint"></div> -->
  </div>

    
  
</template>


<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { listPoint, getPoint, delPoint, addPoint, updatePoint } from "@/api/wrj/point";
import {listInfo,getPlanePostion,getTimeList} from "@/api/wrj/info";
export default {
  name: "map-view",
  dicts: ['sys_jd_name','sys_data_type'],
  data() {
    return {
      form:{
        fq:"",// 时间分区
        rq:"",//日期
        hour:"",// 时间点
        jd:"鉴湖",//街道
        pageNum:1,
        pageSize:99999
      },
      showDataType:'PM2.5(ug/m3)',
      timeList:[],
      polygonColor:'white',
      hours:["00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24"],
      // 街道区块矩形数组对象,只有虚线，没有底色，
      polygonArr: [],
      // pm2.5区块矩形数组对象，有颜色，
      pmPolygonArr:[],

      // 飞机点位对象
      planeArr:[],

      textArr:[],
      pointList:[],
      pm25List:[],
      queryParams:{
        pageNum:1,
        pageSize:99999,
        jd:'鉴湖'
      },
      textFontSize:10,
      timer:null,
      satelliteLayer:null,//官方卫星图层
      defaultLayer:null,
      pmShow: false, // pm2.5信息显示
      pmVal: '', // pm数值
    }
  },
  mounted() {
    this.getTimeList();
    this.$nextTick(()=>{
        this.initAMap();
    })
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    // 切换地图图层
    changeMap(val){
      if(val==1){
        this.polygonColor = 'white'
        
        this.map.add(this.satelliteLayer);
        this.map.remove(this.defaultLayer);
      }else{
        this.polygonColor = 'green'
        this.map.add(this.defaultLayer);
        this.map.remove(this.satelliteLayer);
      }
      this.getAreaPoint();

    },
    // 查询pm2.5数据
    onSubmit(){
      console.log(this.form)
      this.pmShow = true;
      this.getInfoList();
      this.getPlanePostion();
      clearInterval(this.timer);
      this.timer = setInterval(()=>{
        this.getInfoList()
        this.getPlanePostion();
      },10000) 
    }, 

    // 获取飞机定位信息
    getPlanePostion(){
      getPlanePostion(this.form).then(response => {
        let data = response.data;
        console.log(data)
        if(data!=null){
          this.pmVal = data.airData[this.showDataType];
          this.map.remove(this.planeArr); 
          this.planeArr=[];
          
          var marker = new AMap.Marker({
            icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            position: [data.longitude, data.latitude],
            offset: new AMap.Pixel(-13, -30)
          });
          this.planeArr.push(marker) ;
          
          if(this.planeArr.length>0){
            this.map.add(this.planeArr);
          }
        }
        
      });
    },

    // 根据街道，获取pm任务分区时间列表
    getTimeList(){
      getTimeList(this.form).then(response => {
        var data = response.rows;
        if(data!=null){
          data.forEach(item=>{
            this.timeList.push(item.fq)
          })
        }
      //  this.timeList = response.data;
      });
    },

    // 获取PM2.5数值
    getInfoList(){
      listInfo(this.form).then(response => {
        this.pm25List = response.list;
        console.log(this.showDataType)
        // if(this.pm25List.length!=this.pmPolygonArr.length){
          this.drawPmRectangleAndText();
        // }
      });
    },

    //画pm2.5的数值以及文字
    drawPmRectangleAndText(){
      this.map.remove(this.pmPolygonArr);
      this.map.remove(this.textArr);
      this.pmPolygonArr=[];
      this.textArr=[];
      this.pm25List.forEach(element => {
        var southWest = new AMap.LngLat(element.minLng, element.maxLat)
        var northEast = new AMap.LngLat(element.maxLng, element.minLat)

        var bounds = new AMap.Bounds(southWest, northEast)

        var color = this.getColor(element.messageInfo.airData[this.showDataType]);

        console.log(color)
        var rectangle = new AMap.Rectangle({
            bounds: bounds,
            strokeColor:color,
            strokeWeight: 1,
            strokeOpacity:0.5,
            strokeDasharray: [30,10],
            // strokeStyle还支持 solid
            strokeStyle: 'dashed',
            // fillColor:'rgb(0,0,0)',
            fillColor:color,
            fillOpacity:0.7,
            cursor:'pointer',
            zIndex:50,
        })

        var text = new AMap.Text({
          text: element.messageInfo.airData[this.showDataType],
          anchor:'center',
          position: rectangle.getBounds().getCenter(), // 文字位置
          style: {
              // 'padding': '.75rem 1.25rem',
              // 'margin-bottom': '1rem',
              'border-radius': '.25rem',
              'background-color': 'rgba(255,255,255,0)',
              // 'width': '15rem',
              'border-width': 0,
              'text-align': 'center',
              'font-size': this.textFontSize+'px',
              'color': 'white' 
          }
      });
      this.textArr.push(text); 
        this.pmPolygonArr.push(rectangle) ;
      });
      if(this.pmPolygonArr.length>0){
        console.log("dal")
        this.map.add(this.pmPolygonArr);
        this.map.add(this.textArr);
        // this.map.setFitView(this.pmPolygonArr);
      }
    },

    getColor(color){
      if(color>=0 && color<=35){
        return "rgb(53 ,172 ,10)"
      }else if(color>35 && color<=75){
        return "rgb(222, 217 ,7)"
      }else if(color>75 && color<=115){
        return "rgb(242 ,166, 48)"
      }else if(color>115 && color<=150){
        return "rgb(241, 15 ,15)"
      }else if(color>150 ){
        return "rgb(75, 0, 149)"
      }
    },
    initAMap() {
      
      window._AMapSecurityConfig = {
        securityJsCode: "ea203d3756bb886bcdd4833c10c332b9",
      };
      AMapLoader.load({
        key: "475db83acfc1af0cbab24fbdaa34072c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          this.defaultLayer = new AMap.createDefaultLayer()
          this.satelliteLayer = new AMap.TileLayer.Satellite();
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            // viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: [120.577490, 29.932739], // 初始化地图中心点位置
            layers: [this.satelliteLayer],
          });

          // 地图缩放监听事件
          this.map.on('zoomend', this.mapZoomend);
          this.getAreaPoint();
        })
        .catch((e) => {
          console.log(e);
        });
    },

    getAreaPoint(){
        listPoint(this.queryParams).then(response => {
        this.pointList = response.rows;
        console.log(this.pointList)
        this.total = response.total;
        this.loading = false;

        this.pointList.forEach(element => {
            var southWest = new AMap.LngLat(element.minLng, element.maxLat)
            var northEast = new AMap.LngLat(element.maxLng, element.minLat)

            var bounds = new AMap.Bounds(southWest, northEast)

            var rectangle = new AMap.Rectangle({
                bounds: bounds,
                strokeColor:this.polygonColor,
                strokeWeight: 1,
                strokeOpacity:0.5,
                strokeDasharray: [30,10],
                // strokeStyle还支持 solid
                // strokeStyle: 'dashed',
                fillColor:'blue',
                fillOpacity:0,
                cursor:'pointer',
                zIndex:50,
            })
            this.polygonArr.push(rectangle) ;
        });
        this.map.add(this.polygonArr);
        this.map.setFitView(this.polygonArr)
      });
    },

    //地图缩放结束后的方法
    mapZoomend(){
      var zoom = this.map.getZoom();
      if(zoom<=16){
        this.textFontSize=14;
        this.drawPmRectangleAndText()
      }else if(zoom>16 && zoom<=17){
        this.textFontSize=18;
        this.drawPmRectangleAndText()
      }else if(zoom>17 && zoom<=18){
        this.textFontSize=26;
        this.drawPmRectangleAndText()
      }else if(zoom>18){
        this.textFontSize=32;
        this.drawPmRectangleAndText()
      }
      console.log("地图等级：",zoom)
    },

  },
};
</script>


<style lang="scss" scoped>
.pmInfo {
  width: 330px;
  padding: 14px 26px 14px 13px;
  border-radius: 8px;
  box-sizing: border-box;
  border: 1px solid #ebeef5;
  position: fixed;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  overflow: hidden;
  right: -400px;
  z-index: 10;
  top: 60px;
  &.fade-in {
    right: 20px;
    animation: enterFromRight 0.3s ease-in-out;
  }
  .header {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      font-weight: bold;
    }
    .el-icon-close {
      cursor: pointer;
    }
  }
  .content {
    width: 100%;
    margin-top: 10px;
    .pm-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #1a54b1;
    }
  }
}

@keyframes enterFromRight {
  from {
    right: -400px;
  }
  to {
    right: 0;
  }
}
</style>
<style>
 #container{
        padding:0px;
        margin: 0px;
        width: 100%;
        height: 100vh;
  }
    .amap-icon img {
            width: 25px;
            height: 34px;
        }
</style>